<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="机房名称" prop="roomName">
                <el-input
                        v-model="queryParams.roomName"
                        placeholder="请输入机房名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['ar_check:center:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['ar_check:center:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['ar_check:center:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['ar_check:center:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="centerList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="机房名称" align="center" prop="roomName"/>
            <el-table-column label="存放设备容量" align="center" prop="capacity"/>
            <el-table-column label="备注" align="center" prop="notes"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="{row}">
                    <el-button link type="primary" icon="List" @click="showDefect(row)"
                               v-hasPermi="['ar_check:team:query']">
                        查看巡检情况
                    </el-button>
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
                               v-hasPermi="['ar_check:center:edit']">修改
                    </el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(row)"
                               v-hasPermi="['ar_check:center:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改机房对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="centerRef" :model="form" :rules="rules" label-width="110px">
                <el-form-item label="机房名称" prop="roomName">
                    <el-input v-model="form.roomName" placeholder="请输入机房名称"/>
                </el-form-item>
                <el-form-item label="存放设备容量" prop="capacity">
                    <el-input type="number" v-model.number="form.capacity" placeholder="请输入存放设备容量"/>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                    <el-input v-model="form.notes" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-divider content-position="center">设备信息</el-divider>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddDevice">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteDevice">删除</el-button>
                    </el-col>
                </el-row>
                <div class="list">
                    <el-table :data="deviceList" :row-class-name="rowDeviceIndex"
                              @selection-change="handleDeviceSelectionChange" ref="device">
                        <el-table-column type="selection" width="50" align="center"/>
                        <el-table-column label="序号" align="center" prop="index" width="50"/>
                        <el-table-column label="设备名称" prop="deviceName" width="150">
                            <template #default="{row}">
                                <el-select v-model="row.deviceId" clearable placeholder="请输入设备"
                                           @change="checkClick(row)">
                                    <el-option v-for="item in deviceArr" :key="item.deviceId" :label="item.deviceName"
                                               :value="item.deviceId" :disabled="item.disable"/>
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <defect-list ref="defectTab"/>
    </div>
</template>

<script setup>
import { listCenter, getCenter, delCenter, addCenter, updateCenter } from '@/api/ar_check/center'
import { deviceListAll } from '@/api/ar_check/device.js'
import DictTag from '@/components/DictTag/index.vue'
import DefectList from '@/views/ar_check/defects/components/defectList.vue'
import { getRoomByIdDefect } from '@/api/ar_check/defects.js'

defineOptions({
    name: 'Center'
})

const { proxy } = getCurrentInstance()

const centerList = ref([])
const deviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedDevice = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const deviceArr = ref([])

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomName: null,
    },
    rules: {
        roomName: [
            { required: true, message: '机房名称不能为空', trigger: 'blur' }
        ],
        capacity: [
            { required: true, message: '存放设备容量不能为空', trigger: 'blur' }
        ],
    }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询机房列表 */
function getList() {
    loading.value = true
    listCenter(queryParams.value).then(response => {
        centerList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        roomId: null,
        roomName: null,
        capacity: null,
        notes: null
    }
    deviceList.value = []
    proxy.resetForm('centerRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.roomId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getDeviceList()
    open.value = true
    title.value = '添加机房'
}

/** 修改按钮操作 */
async function handleUpdate(row) {
    reset()
    const _roomId = row.roomId || ids.value
    await getDeviceList()
    const { data } = await getCenter(_roomId)
    form.value = data
    deviceList.value = data.deviceList.map(value => {
        return { ...value, id: value.deviceId }
    })
    open.value = true
    title.value = '修改机房'
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['centerRef'].validate(valid => {
        if (valid) {
            form.value.deviceList = deviceList.value
            if (form.value.roomId != null) {
                updateCenter(form.value).then(response => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                addCenter(form.value).then(response => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _roomIds = row.roomId || ids.value
    proxy.$modal.confirm('是否确认删除机房编号为"' + _roomIds + '"的数据项？').then(function () {
        return delCenter(_roomIds)
    }).then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

/** 设备序号 */
function rowDeviceIndex({ row, rowIndex }) {
    row.index = rowIndex + 1
}

/** 设备添加按钮操作 */
function handleAddDevice() {
    let obj = {}
    obj.deviceName = ''
    obj.id = ''
    deviceList.value.push(obj)
}

/** 设备删除按钮操作 */
function handleDeleteDevice() {
    if (checkedDevice.value.length === 0) {
        proxy.$modal.msgError('请先选择要删除的设备数据')
    } else {
        const devices = deviceList.value
        const checkedDevices = checkedDevice.value
        checkedDevices.forEach(value => {
            const data = devices.find(val => val.index === value)
            disableCheck(data.deviceId, false)
            data.id = ''
        })
        deviceList.value = devices.filter(function (item) {
            return checkedDevices.indexOf(item.index) === -1
        })
    }
}

/*设备列表*/
async function getDeviceList() {
    const { data } = await deviceListAll()
    deviceArr.value = data.map(value => {
        return { ...value, disable: !!value.location }
    })
}

/** 复选框选中数据 */
function handleDeviceSelectionChange(selection) {
    checkedDevice.value = selection.map(item => item.index)
}

/*点击选中*/
function checkClick(row) {
    if (row.deviceId) {
        if (row.id)
            disableCheck(row.id, false)
        row.id = row.deviceId
        disableCheck(row.deviceId, true)
    } else {
        disableCheck(row.id, false)
        row.id = ''
    }
}

/*禁用开关*/
function disableCheck(id, flag) {
    if (!id) return
    const device = deviceArr.value.find(value => value.deviceId === id)
    device.disable = flag
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('ar_check/center/export', {
        ...queryParams.value
    }, `center_${new Date().getTime()}.xlsx`)
}

// 查看缺陷设备
async function showDefect({ roomId, roomName }) {
    const { data } = await getRoomByIdDefect(roomId)
    proxy.$refs.defectTab.open(data, roomName)
}

getList()
</script>
<style>
.list .el-table__header {
    width: 100% !important;
}

.list .el-table__body {
    width: 100% !important;
}
</style>
